﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using LJF.ManageSYS.Authorize;
using LJF.Models;
using LJF.Models.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace LJF.ManageSYS.Controllers
{
    [Route("api/[controller]/[action]")]
    public class LoginController : BaseController
    {
        ManageSys_DATAContext dataMD;
        private readonly IConfiguration _configuration;

        public LoginController(ManageSys_DATAContext _dataMD, IConfiguration configuration)
        {
            dataMD = _dataMD;
            _configuration = configuration;
        }


        [HttpGet]
        [SysAuthorize(Permission ="系统管理权限",Show =true)]//添加Authorize标签，可以加在方法上，也可以加在类上
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpGet]
        public ResponseData NoPermission()
        {
            return Fail(new { url = "测试路径" }, "抱歉，您没有权限，请联系管理员！");
        }

        [HttpPost]
        public ResponseData Login(string phone, string pwd)
        {
            if ((phone != "" && pwd != "") && (phone != null && pwd != null))
            {
                XtUser user = dataMD.XtUser.FirstOrDefault(p => p.Phone == phone);
                if (user == null)
                {
                    return Fail("该号码未注册！");
                }
                else if (user.Pwd != pwd)
                {
                    return Fail("您输入的密码有误！");
                }
                else
                {
                    // push the user’s name into a claim, so we can identify the user later on.
                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Name, user.Name),
                        new Claim("SNo",user.Sno)
                    };
                    //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                    //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
                    /**
                     * Claims (Payload)
                        Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段，下面节选一些字段:
                        iss: The issuer of the token，token 是给谁的  发送者
                        audience: 接收的
                        sub: The subject of the token，token 主题
                        exp: Expiration Time。 token 过期时间，Unix 时间戳格式
                        iat: Issued At。 token 创建时间， Unix 时间戳格式
                        jti: JWT ID。针对当前 token 的唯一标识
                        除了规定的字段外，可以包含其他任何 JSON 兼容的字段。
                     * */
                    var token = new JwtSecurityToken(
                        issuer: "jwttest",
                        audience: "jwttest",
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(30),
                        signingCredentials: creds);

                    return Success(new { access_token = new JwtSecurityTokenHandler().WriteToken(token) }, "登录成功");
                }

            }
            else
            {
                return Fail("手机号码或者密码为空值，请检查！");
            }
        }

        [HttpGet]
        public void LoginOut()
        {
            HttpContext.Response.Redirect("");
        }
    }
}